package com.spdg.ring;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.wolf.base.ICallBack;
import cn.wolf.http.HttpCallBack;
import cn.wolf.tools.AlertHelper;
import cn.wolf.tools.Base64Util;
import cn.wolf.tools.CommonUtils;
import cn.wolf.tools.SdCardTool;
import cn.wolf.tools.SharedPreferencesUtil;

import com.spdg.ring.bo.CheckVersionBo;
import com.spdg.ring.bo.WeiboBo;
import com.spdg.ring.common.Config;
import com.spdg.ring.common.Key;
import com.spdg.ring.entity.VersionEntity;
import com.spdg.ring.entity.VersionEntity.Content;
import com.spdg.ring.resp.VersionResp;
import com.spdg.ring.util.ClearUtil;
import com.spdg.ring.widget.AccessTokenKeeper;
import com.umeng.fb.UMFeedbackService;
import com.weibo.sdk.android.Oauth2AccessToken;

public class MoreActivity extends RingBaseActivity {

	private LinearLayout mClearCache;
	private LinearLayout mCheckUpdate;
	private LinearLayout mAbout;
	private LinearLayout mFeedback;
	private LinearLayout mWeiboBtn;
	private LinearLayout m2g3gSetting;

	private View m2g3gImageSetting;
	private TextView mWeiboTv;
	private TextView mFileLength; // 缓存文件大小，单位mb

	private View mOffline; // 离线下载

	private CheckVersionBo mCheckVerBo;
	private WeiboBo mWeiboBo;
	private Oauth2AccessToken token;
	private String versionUpdateUrl = ""; // 版本升级下载地址

	public static final int H_SHOW_CACHE_FILE_SIZE = 0x1; // 显示缓存大小
	public static final int H_CLEAR_SUCCESS = 0X3; // 清楚缓存成功
	ProgressDialog progressDialog;
	private Handler mHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			int what = msg.what;
			if (what == H_SHOW_CACHE_FILE_SIZE) {
				long length = (Long) msg.obj;
				showCacheFileSize(length);

			} else if (what == H_CLEAR_SUCCESS) {
				progressDialog.cancel();
				long length = (Long) msg.obj;
				showCacheFileSize(length);
				Toast.makeText(mContext, getString(R.string.clear_cache_success),
						Toast.LENGTH_SHORT).show();
			}

		}
	};

	@Override
	protected void initComponents() {
		mWeiboBtn = (LinearLayout) findViewById(R.id.more_bind_weibo);
		mClearCache = (LinearLayout) findViewById(R.id.more_clear_cache);
		mCheckUpdate = (LinearLayout) findViewById(R.id.more_check_update);
		mFeedback = (LinearLayout) findViewById(R.id.more_feedback);
		mAbout = (LinearLayout) findViewById(R.id.more_about);
		mWeiboTv = (TextView) findViewById(R.id.bind_weibo_tv);
		m2g3gImageSetting = findViewById(R.id.image_2g3g_setting);
		m2g3gSetting = (LinearLayout) findViewById(R.id.more_2g3g_image);
		mOffline = findViewById(R.id.more_offline);
		mFileLength = (TextView) findViewById(R.id.file_length);

		m2g3gSetting.setOnClickListener(new On2g3gImageSetting());

		progressDialog = new ProgressDialog(mContext);

		// 设置监听器
		mWeiboBtn.setOnClickListener(new OnBindWeiboListener());
		mClearCache.setOnClickListener(new OnClearCacheListener());
		mCheckUpdate.setOnClickListener(new OnCheckUpdateListener());
		mFeedback.setOnClickListener(new OnFeedBackClickListener());
		mAbout.setOnClickListener(new OnAboutListener());

		mOffline.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(mContext, ZipDownloadActivity.class);
				startActivity(intent);
			}
		});
	}

	@Override
	protected void initData() {
		mWeiboBo = new WeiboBo(mContext, new WeiboCallBack());

		mCheckVerBo = new CheckVersionBo(mContext, new CheckVerCallBack());

		show2g3gSetting();

		queryCacheFileSize();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 初始化微博
		initWeibo();
	}

	private void queryCacheFileSize() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				long length = SdCardTool.getSize(Config.SDCARD_ROOT_DIR);
				Message msg = mHandler.obtainMessage();
				msg.obj = length;
				msg.what = H_SHOW_CACHE_FILE_SIZE;
				mHandler.sendMessage(msg);
			}
		}).start();
	}

	private void showCacheFileSize(long length) {
		int size = 0;
		String showSize = "";
		if (length >= 1024) { // 转化为kb
			size = (int) length / 1024;

			if (size >= 1024) {
				size = size / 1024;
				showSize = "(" + size + "M" + ")";
			} else {
				showSize = "(" + size + "KB" + ")";
			}
		}
		mFileLength.setText(showSize);
	}

	/**
	 * 初始化微博
	 */
	private void initWeibo() {
		// 初始化微博
		token = AccessTokenKeeper.readAccessToken(mContext);

		if (token != null && token.isSessionValid()) {
			mWeiboTv.setText(R.string.menu_unbind_weibo);
		} else {
			mWeiboTv.setText(R.string.menu_bind_weibo);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (mWeiboBo.mSsoHandler != null) {
			mWeiboBo.mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	class WeiboCallBack implements ICallBack {

		@Override
		public void call(String type) {
			if (WeiboBo.TYPE_WEIBO_BIND_SUCCESSFUL.equals(type)) {
				CommonUtils.showToast(mContext, getString(R.string.weibo_auth_ok));
			} else if (WeiboBo.TYPE_WEIBO_CANCEL.equals(type)) {
				CommonUtils.showToast(mContext, getString(R.string.weibo_auth_unbind));
			} else if (WeiboBo.TYPE_WEIBO_UNBIND_SUCCESSFUL.equals(type)) {
				CommonUtils.showToast(mContext, getString(R.string.weibo_auth_unbind_ok));
			}

			// 初始化微博
			initWeibo();
		}
	}

	class CheckVerCallBack implements HttpCallBack<VersionResp> {

		@Override
		public void call(VersionResp response) {
			progressDialog.cancel();
			if (response.isSuccess()) {

				VersionEntity entity = response.getEntity();
				if (entity != null) {
					Content content = entity.getContent();
					String update = Base64Util.decode2String(content.getUpdate());
					versionUpdateUrl = Base64Util.decode2String(content.getUrl());

					if (CheckVersionBo.VERSION_UPDATE.equals(update)) {
						String tip = getString(R.string.check_version_new);
						AlertHelper.showConfirm(mContext, tip, new OnConfirmClickListener(), null);
					} else {
						Toast.makeText(mContext, getString(R.string.check_version_newest),
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(mContext, getString(R.string.check_version_newest),
							Toast.LENGTH_SHORT).show();
				}
			}
		}

		@Override
		public void progress(Object... obj) {
		}

		@Override
		public void onNetWorkError() {
			Toast.makeText(mContext, getString(R.string.network_error), Toast.LENGTH_SHORT).show();
		}
	}

	// 升级版本
	class OnConfirmClickListener implements android.content.DialogInterface.OnClickListener {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			// 调用本地浏览器进行版本下载
			Uri uri = Uri.parse(versionUpdateUrl);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
		}
	}

	class OnBindWeiboListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// 初始化微博
			token = AccessTokenKeeper.readAccessToken(mContext);

			if (token != null && token.isSessionValid()) {
				mWeiboBo.unBindAuthor();
			} else {
				mWeiboBo.authorize();
			}
		}
	}

	/**
	 *  清除缓存
	 *  1、离线包
	 *  2、图片
	 */
	class OnClearCacheListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			AlertHelper.showConfirm(mContext, getString(R.string.clear_cache),
					getString(R.string.clear_cache_dialog_message),
					getString(R.string.clear_cache_dialog_yes),
					getString(R.string.clear_cache_dialog_no),
					new DialogInterface.OnClickListener() { // 确定

						@Override
						public void onClick(DialogInterface dialog, int which) {
							progressDialog.cancel();
							progressDialog.setMessage("清理缓存中..");
							progressDialog.show();
							new Thread(new Runnable() {

								@Override
								public void run() {
									ClearUtil.clearCache(mContext);
									long length = SdCardTool.getSize(Config.SDCARD_ROOT_DIR);
									Message msg = mHandler.obtainMessage();
									msg.obj = length;
									msg.what = H_CLEAR_SUCCESS;
									mHandler.sendMessage(msg);
								}
							}).start();
						}
					}, null);
		}
	}

	// 检查更新
	class OnCheckUpdateListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			progressDialog.cancel();
			progressDialog.setMessage("检查更新中..");
			progressDialog.show();
			mCheckVerBo.checkVersion();
		}

	}

	// 意见反馈
	class OnFeedBackClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			UMFeedbackService.openUmengFeedbackSDK(mContext);
		}
	}

	// 关于
	class OnAboutListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent i = new Intent(MoreActivity.this, AboutActivity.class);
			startActivity(i);
		}
	}

	// 2g3g开关
	class On2g3gImageSetting implements OnClickListener {
		@Override
		public void onClick(View v) {
			change2g3gSetting();
		}
	}
	
	private void show2g3gSetting(){
		boolean timeinterval = SharedPreferencesUtil.getBoolean(mContext, Key.K_2G3G_IMAGE_SETTING);
		m2g3gImageSetting.setEnabled(timeinterval);
	}

	private void change2g3gSetting() {
		boolean timeinterval = SharedPreferencesUtil.getBoolean(mContext, Key.K_2G3G_IMAGE_SETTING);
		if (timeinterval) {
			m2g3gImageSetting.setEnabled(false);
			SharedPreferencesUtil.setBoolean(mContext, Key.K_2G3G_IMAGE_SETTING, false);
		} else {
			m2g3gImageSetting.setEnabled(true);
			SharedPreferencesUtil.setBoolean(mContext, Key.K_2G3G_IMAGE_SETTING, true);
		}
	}

	@Override
	protected int getMainContentViewId() {
		return R.layout.act_more;
	}

	@Override
	protected Class<?> getResouceClass() {
		return R.class;
	}

	@Override
	protected String getEventID() {
		return getString(R.string.event_activity_more);
	}
}
